<?php
  	require_once('../utils/logged_in.php');
	require_once('../utils/query.php');


$user1 = $drupaluid;
$user2 = $_POST["uid"]; // The facebook id of the person clicked on to trade with
$user2 = execute_query("SELECT drupaluid FROM facebookUser WHERE facebookID='%s'", $user2); // Get the drupal id corresponding to the facebook id of the user to trade with
$user2 = mysql_result($user2, 0);
$cards = $_POST["cards"];

$cards = explode("~",$cards); // Break apart string into an array where each index separates part of the string based on the delimiter ~ 

$tradeID = execute_query("SELECT tradeid FROM Trade WHERE (userid1='%s' AND userid2='%s') OR (userid1='%s' AND userid2='%s')", $user1, $user2, $user2, $user1);

if(!$row = mysql_fetch_array($tradeID))
{
	execute_query("INSERT INTO Trade (userid1, userid2) VALUES ('%s', '%s')", $user1, $user2);
	$tradeID = execute_query("SELECT tradeid FROM Trade WHERE (userid1='%s' AND userid2='%s') OR (userid1='%s' AND userid2='%s')", $user1, $user2, $user2, $user1);
	$tradeID = mysql_result($tradeID, 0);
}
else
{
$tradeID = $row[0];
}

$i = 0;

for($i=1;$i<count($cards);$i++)
{
	$posID = execute_query("SELECT possessionid FROM Possession WHERE cardid='%s' AND userid='%s'", $cards[$i], $user1);
	$control = 0;
	while($rows = mysql_fetch_array($posID))
	{
		$check = execute_query("SELECT * FROM TradePossession WHERE tradeid='%s' AND possessionid='%s'", $tradeID, $rows[0]);
		if($check = mysql_fetch_array($check))
		{
		}
		else
		{
			if($control==0)
			{
				$result = execute_query("INSERT INTO TradePossession (tradeid, possessionid) VALUES ('%s', '%s')", $tradeID, $rows[0]);
				$control = 1;
			}
		}
		
	}
execute_query("UPDATE Trade SET user1accepted=0, user2accepted=0 WHERE tradeid='%s'", $tradeID);
	
}



echo $tradeID;

?>